<?php

/**
 * Subclass for performing query and update operations on the 'user_network_code' table.
 *
 * 
 *
 * @package lib.model
 */ 
class UserNetworkCodePeer extends BaseUserNetworkCodePeer
{
	
	static public function generateNetworkCodeForUser(User $user){
		//Eerst eventuele oude code ophalen
		$c = new Criteria();
		$c->add(UserNetworkCodePeer::USER_ID,$user->getId());
		$nwcode =  UserNetworkCodePeer::doSelectOne($c);
		if(!$nwcode) $nwcode = new UserNetworkCode();
		
		$hash = Util::createUniqueHash(time());
		$code = sprintf('%s-%s',substr($hash,8,8),$user->getId());
		$nwcode->setCode($code);
		$nwcode->setUserId($user->getId());
		$nwcode->setValidUntil(strtotime('now +1 hour'));
		$nwcode->save();
		//Voor de zekerheid ook de id van de gegenereerde code toevoegen aan code!
		$nwcode->setCode(sprintf('%s-%s',$nwcode->getId(),$nwcode->getCode()));
		$nwcode->save();
		return $nwcode;
	}
	
	static public function getUserForCode($code){
		$c = new Criteria();
		$c->add(UserNetworkCodePeer::CODE,$code);
		$networkcode = self::doSelectOne($c);
		if(!$networkcode) throw new sfException('Code not found!');
		$user = $networkcode->getUser();
		if(!$user) throw new sfException('User not found!');
		if($networkcode->getValidUntil('U') < time()) throw new sfException('This code is not valid anymore, please generate a new one');
		return $user;
	}
}
